package com.fmatos.carcontrol.view;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.fmatos.carcontrol.R;
import com.fmatos.carcontrol.bluetooth.BluetoothManager;

public class MainActivity extends Activity {

	protected static final String TAG = MainActivity.class.getSimpleName();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		
		private Button btnPair;
		private Button btnScan;
		
		private BluetoothManager bluetoothManager;
		private TextView txtEcho;
		private TextView txtPing;

		private Thread thGetMessages;
		
		public PlaceholderFragment() {
		}
		
		@Override
		public void onPause() {
			if  ( bluetoothManager != null ) {
				bluetoothManager.releaseResources();
			}
			
			if ( thGetMessages != null ) {
				thGetMessages.interrupt();
			}
			super.onPause();
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			
			btnScan = (Button) rootView.findViewById(R.id.btnScan);
			btnScan.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),BluetoothPickerActivity.class);
					startActivity(intent);					
				}
			});
			
			btnPair = (Button) rootView.findViewById(R.id.btnPair);
			
			btnPair.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Log.i(TAG,"Scanning for bluetooth");
					bluetoothManager = new BluetoothManager(getActivity());
					if ( bluetoothManager.isBluetoothActive() ) {
						 Object thBluetooth = bluetoothManager.pair(); 
						if ( thBluetooth == null ) {
							Toast.makeText(getActivity(), "Could not get socket to bluetooth device", Toast.LENGTH_LONG).show();
						}
					}
				}
			});
			
			
			txtEcho = (TextView) rootView.findViewById(R.id.txtEcho);
			txtPing = (TextView) rootView.findViewById(R.id.txtPing);
			
			createCommandButton(rootView,R.id.btnUp, "up"); 
			createCommandButton(rootView,R.id.btnDown, "down");
			createCommandButton(rootView,R.id.btnLeft, "left");
			createCommandButton(rootView,R.id.btnRight, "right");
			
			thGetMessages = new Thread(new Runnable() {
				
				@Override
				public void run() {
					fillTextEcho();
				}
			});
			
			thGetMessages.start();
			return rootView;
		}
		
		private void createCommandButton(View rootView, int id,final String command) {
			
			Button button = (Button) rootView.findViewById(id);
			button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if ( bluetoothManager != null && bluetoothManager.isPaired() ) {
						bluetoothManager.sendMessage(command);
					}
					
				}
			});
		}
		
		private void fillTextEcho() {
			
			while (true) {
				if ( txtEcho != null && txtPing != null && bluetoothManager != null) {

					String message = bluetoothManager.getMessage();
					while ( message != null ) {
						final String scopedMessage = message;
						final TextView scopedButton;
						if ( message.contains("The number")) {
							scopedButton = txtEcho;
						} else {
							scopedButton = txtPing;
						}
						
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								scopedButton.setText(scopedMessage);
							}
						});

						message = bluetoothManager.getMessage();
					}

				}
				try {
					// gives some time for buffer to fill
					thGetMessages.sleep(300);
				} catch (InterruptedException e) {
					Log.d(TAG,"Thread interrupted");
					
				} 
			}
		}
	}
}
